package com.naiterui.ehp.bs.b2c.pharmacy.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.naiterui.ehp.bs.b2c.order.entity.LogisticseCompany;
import com.naiterui.ehp.bs.b2c.order.repository.ILogisticseCompanyRepository;
import com.naiterui.ehp.bs.b2c.pharmacy.entity.Warehouse;
import com.naiterui.ehp.bs.b2c.pharmacy.repository.IWarehouseRepository;
import com.naiterui.ehp.bs.b2c.pharmacy.service.IWarehouseSuperviseService;
import com.naiterui.ehp.bs.b2c.pharmacy.vo.SuperviseWarehouseVO;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author luao
 * @date 2021/6/21 11:16 上午
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class WarehouseSuperviseServiceImpl implements IWarehouseSuperviseService {

    private final IWarehouseRepository warehouseRepository;
    private final ILogisticseCompanyRepository logisticseCompanyRepository;

    @Override
    public List<SuperviseWarehouseVO> warehouseList(Date startDate, Date endDate, Long warehouseId) {
        // 商家列表
        List<Warehouse> warehouseList = new ArrayList<>();
        if (warehouseId == null) {
            warehouseList =
                warehouseRepository.findByStatusAndChangedAtBetween(Warehouse.STATUS_NORMAL, startDate, endDate);
        } else {
            Warehouse warehouse = warehouseRepository.get(warehouseId);
            if (warehouse == null) {
                return null;
            }
            warehouseList.add(warehouse);
        }
        if (CollectionUtil.isEmpty(warehouseList)) {
            return null;
        }
        // 查询所有物流公司信息
        List<LogisticseCompany> logisticseCompanys = logisticseCompanyRepository.findAll();
        List<String> logisticsNames = logisticseCompanys.stream().map(LogisticseCompany::getName).collect(Collectors.toList());
        String logisticsName = CollectionUtil.join(logisticsNames, "|");
        List<SuperviseWarehouseVO> result = new ArrayList<>();
        for (Warehouse warehouse : warehouseList) {
            result.add(SuperviseWarehouseVO.builder()
                    .warehouseId(warehouse.getId())
                    .warehouseCode(warehouse.getCode())
                    .warehouseName(warehouse.getName())
                    .isOwnLogistics(0)
                    .logisticsName(logisticsName)
                    .validFlag(warehouse.getStatus() == Warehouse.STATUS_NORMAL ? 1 : 0)
                    .build());
        }
        return result;
    }
}
